/**
 * @Created by WebStrom
 * @Author: 打字桶
 * @Desc:
 */
import APIConfig from "../config/api";
import exceptionMessage from "../config/exception-message";
import wxToPromise from "./wx";
import cache from "../enum/cache";
import User from "../model/user";
import {createStoreBindings} from "mobx-miniprogram-bindings";
import {timStore} from "../store/tim";

class Http {
  // 调用静态方法不用new
  static async request({url, data, method = 'get', refetcg = true}) {
    let res
    // 异常情况：1.代码写错 2.无网络 3.服务端超时
    try {
      // try内部的变量属于局部变量，无法被上级作用域使用
      res = await wxToPromise('request', {
        url: APIConfig.baseUrl + url,
        data,
        method,
        header: {
          token: wx.getStorageSync(cache.TOKEN)
        }
      })
    } catch (e) {
      Http._showError(-1)
      throw new Error(e.errMsg)
    }

    // 全局统一响应、异常处理
    // TODO 请求成功
    if (res.statusCode < 400) {
      return res.data.data
    }
    // TODO 请求失败
    if (res.statusCode === 401) {
      this.storeBindings = createStoreBindings(this, {
        store: timStore,
        fields: ['sdkReady'],
        actions: {timLogout: 'logout'},// 要绑定哪个状态,会绑定到data里
      })
      //TODO 令牌相关操作
      console.log(res.data.error_code)
      if (res.data.error_code === 10001) {
        // 10001时需要退出登录状态
        if (this.sdkReady) {
          //先判断不然直接调用logout方法会报错
          this.timLogout()
        }
        wx.navigateTo({
          url: '/pages/login/login'
        })
        throw Error('请求未携带令牌')
      }
      if (refetcg) {
        return await Http._refetch(url, data, method, refetcg)
      }
      if (this.sdkReady) {
        //先判断不然直接调用logout方法会报错
        this.timLogout()
      }

    }
    // 接口错误信息，一定要看清楚文档，哪些适合直接展示出去，哪些不合适
    Http._showError(res.data.error_code, res.data.message)
    // 处理异常
    const error = Http._generaMessage(res.data.message)
    // 异常抛给上一层
    throw Error(error)
  }

  /**
   * 重新发起请求
   * @param data
   */
  static async _refetch(data) {
    await User.login()
    data.refetch = false //避免一直重复发起令牌请求
    return await Http.request(data)
  }

  static _showError(errorCode, message) {
    let title = ''
    const errorMessage = exceptionMessage[errorCode]
    title = errorMessage || message || '未知异常'
    title = Http._generaMessage(title)
    wx.showToast({
      title,
      icon: 'none',
      duration: 3000
    })
  }

  // 处理异常提示信息
  static _generaMessage(message) {
    return typeof message === 'object' ? Object.values(message).join(';') : message
  }
}

export default Http